import Vue from 'vue'
import messageVue from './message.vue'
const defaults = {
  show: false,
  text: '',
  duration: '3000',
  type: ''
}
let instances = []
const MessageVueConstructor = Vue.extend(messageVue)
MessageVueConstructor.prototype.close = function () {
  var vm = this
  this.$on('after-leave', _ => {
    if (vm.$el && vm.$el.parentNode) {
      vm.$el.parentNode.removeChild(vm.$el)
    }
    this.$destroy()
  })
  let len = instances.length

  for (let i = 0; i < len; i++) {
    let dom = instances[i].$el

    dom.style['top'] = parseInt(dom.style['top'], 10) - instances[i].$el.offsetHeight - 16 + 'px'
  }
  instances.splice(0, 1)
  vm.show = false
}
const messageBox = (options = {}) => {
  if (Vue.prototype.$isServer) return
  let verticalOffset = 20
  options = Object.assign({}, defaults, options)
  let parent = document.body
  let instance = new MessageVueConstructor({
    el: document.createElement('div'),
    data: options
  })

  instances.forEach(item => {
    verticalOffset += item.$el.offsetHeight + 16
  })

  instance.verticalOffset = verticalOffset
  instances.push(instance)
  parent.appendChild(instance.$el)
  Vue.nextTick(() => {
    instance.show = true
    setTimeout(function () {
      instance.close()
    }, options.duration)
  })

  return instance
}

export default messageBox
